<template>
  <div>
    <!-- breadcrumb-area start -->
    <div class="breadcrumb-area">
      <div class="container">
        <div class="row">
          <div class="col-12">
            <div class="row breadcrumb_box align-items-center">
              <div class="col-lg-6 col-md-6 col-sm-12 text-center text-md-left">
                <h2 class="breadcrumb-title">购物车</h2>
              </div>
              <div class="col-lg-6 col-md-6 col-sm-12">
                <!-- breadcrumb-list start -->
                <ul class="breadcrumb-list text-center text-md-right">
                  <li class="breadcrumb-item"><router-link to="/">首页</router-link></li>
                  <li class="breadcrumb-item active">购物车</li>
                </ul>
                <!-- breadcrumb-list end -->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- breadcrumb-area end -->

    <!-- Cart Area Start -->
    <div class="cart-main-area pt-100px pb-100px">
      <div class="container">
        <h3 class="cart-page-title">Your cart items</h3>
        <div class="row">
          <div class="col-lg-12 col-md-12 col-sm-12 col-12">
            <div class="cart">
              <div class="group_btn"></div>
              <el-card>
              <el-table
                ref="multipleTable"
                :data="tableData"
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
               <el-table-column
                type="selection"
                width="55">
                </el-table-column>
                <el-table-column prop="bookImages" label="图书图片" width="200">
                  <template slot-scope="scope">
                    <el-image
                      style="width: 180px; height: 180px"
                      :src="$store.state.imgURLPre+scope.row.bookImages"
                      :preview-src-list="[scope.row.bookImages]"
                    >
                    </el-image>
                  </template>
                </el-table-column>
               
                <el-table-column
                  prop="bookTitle"
                  label="图书标题"
                ></el-table-column>
                <el-table-column
                  prop="bookNewPrice"
                  label="现价"
                ></el-table-column>
                <el-table-column
                  prop="cartAmount"
                  label="数量"
                  width="150"
                >
                <template slot-scope="scope">
                     <el-input-number v-model="scope.row.cartAmount" @change="handleChange(scope.row)" :min="1"  label="描述文字" style="margin-left:-10px"></el-input-number>
                </template>
                </el-table-column>
                <el-table-column
                  label="金额"
                >
                <template slot-scope="scope">
                    {{(scope.row.bookNewPrice*scope.row.cartAmount).toFixed(2)}}
                </template>
                </el-table-column>

                 <el-table-column
                  prop="addTime"
                  label="添加时间"
                  width="200"
                  sortable
                >
                <template slot-scope="scope">
                 {{scope.row.addTime | dataFomart}}
                </template>
             </el-table-column>
                

                <el-table-column fixed="right" label="操作" width="200">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      icon="el-icon-search"
                      circle
                      @click="showInfo(scope.row)"
                    ></el-button>
                    <el-popconfirm
                      @confirm="del(scope.row.id)"
                      title="确定删除？"
                    >
                      <el-button
                        type="danger"
                        icon="el-icon-delete"
                        circle
                        slot="reference"
                        style="margin-left: 10px"
                      ></el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
              </el-card>
               <div style="margin-top: 20px">
              <el-row>
                  <el-col :span="4">
                    <el-popconfirm
                      @confirm="deleteCheckout"
                      title="确定删除？"
                    ><el-button slot="reference">批量删除</el-button></el-popconfirm></el-col>
                  <el-col :span="6" :offset="12">{{totalNumber}}件商品总计（不含运费）{{totalPrice.toFixed(2)}}元</el-col>
                  <el-col :span="2"> <el-button @click="toCheckout">去结算</el-button></el-col>
              </el-row>
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- Cart Area End -->

    <el-dialog :visible.sync="dialogVisible" width="50%">
      <div class="modal-body">
        <div class="row">
          <div class="col-md-5 col-sm-12 col-xs-12 mb-lm-30px mb-sm-30px">
            <!-- Swiper -->
            <div class="swiper-container gallery-top mb-4">
              <img
                class="img-responsive m-auto"
                :src="$store.state.imgURLPre+info.bookImages"
                alt=""
              />
            </div>
          </div>
          <div class="col-md-7 col-sm-12 col-xs-12">
            <div class="product-details-content quickview-content">
              <h2>{{ info.bookTitle }}</h2>
              <p class="reference">
                作者:<span>{{ info.bookAuthors }}</span>
              </p>
              <div class="pro-details-rating-wrap">
                <div class="rating-product">
                  <i class="ion-android-star"></i>
                  <i class="ion-android-star"></i>
                  <i class="ion-android-star"></i>
                  <i class="ion-android-star"></i>
                  <i class="ion-android-star"></i>
                </div>
                <span class="read-review"
                  ><a class="reviews" href="#"
                    >剩余数量({{ info.bookQuantityInput }})</a
                  ></span
                >
              </div>
              <div class="pricing-meta">
                <ul>
                  <li class="old-price not-cut">￥{{ info.bookNewPrice }}</li>
                </ul>
              </div>
              <p class="quickview-para" v-html="info.bookDescribe"></p>

           
              <div class="pro-details-wish-com">
                <div class="pro-details-wishlist">
                  <!-- <a @click="addWishList(info.id)"><i class="el-icon-star-on" v-if="wishList.some(e=>e.id===info.id)">已收藏</i>
                              <i class="el-icon-star-off" v-else>添加到收藏</i></a
                  > -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer"> </span>
    </el-dialog>
  </div>
</template>

<script>
import API from "@/api/request";
const url = "/api/msslyyBook"
export default {
  name: "BookShopCart",

  components: {},

  directives: {},

  data() {
    return {
      dialogVisible: false,
      user: {},
      multipleSelection: [], //存放已选择的数据
      //表格中的数据
      tableData: [],
      info: {},
      deleteItems:[],
    };
  },
  filters:{
     dataFomart(date){
       let dt = new Date(date);//实例化时间对象
       let y = dt.getFullYear();
       let m = dt.getMonth() + 1>10?(dt.getMonth()+ 1):"0"+(dt.getMonth()+ 1);
       let d = dt.getDate()>10?dt.getDate():"0"+dt.getDate(); 
       let hh=dt.getHours()>=10?dt.getHours():"0"+dt.getHours();
       let mm=dt.getMinutes()>=10?dt.getMinutes():"0"+dt.getMinutes();
       let ss=dt.getSeconds()>=10?dt.getSeconds():"0"+dt.getSeconds();
      //笨方法  return y + '-' + m + '-' + d
      //官方方法  注意引号，是tab键上面的符号（ES6的语法）
      return `${y}-${m}-${d}  ${hh}:${mm}:${ss}`
    },},
  watch: {
      //监听showcart的变化
    "$store.state.removeCartItem": function () {
      if (this.$store.state.removeCartItem === true) {
        this.load();
      }
    },
  },
  computed: {
    // 总价
    totalPrice() {
      var price_total = 0;
      for (var i = 0; i < this.multipleSelection.length; i++) {
        price_total +=
          this.multipleSelection[i].bookNewPrice * this.multipleSelection[i].cartAmount;
      }
      return price_total;
    },
    // 总数
    totalNumber() {
      var number_total = 0;
      for (var i = 0; i < this.multipleSelection.length; i++) {
        number_total += this.multipleSelection[i].cartAmount;
      }
      return number_total;
    },
  },
  mounted() {},
  created() {
    this.user = sessionStorage.getItem("user1")
      ? JSON.parse(sessionStorage.getItem("user1"))
      : {};
    this.load();
  },
  methods: {
    del(id){
      API.delete(`/api/msslyyCart/${this.user.id}/${id}`).then((res) => {
        this.$message({
          type: "success",
          message: "删除成功"
        })
        this.load()
      });
    },
    //批量删除
    deleteCheckout(flag=true){
      if (this.deleteItems.length>0) {
        let carts=JSON.stringify(this.deleteItems)
      const item=carts.slice(1,-1)
      API.post(`/api/msslyyCart/delete/${item}/${this.user.id}`)
      .then((res) => {
        if (flag) {
           this.$message({
          type: "success",
          message: "批量删除成功"
        })
        }
        
        this.load();
      });
      }
      
    },
    showInfo(item) {
      this.info = item;
      this.dialogVisible = true;
    },
    load() {
      API.get(url + "/getCartById/" + this.user.id, {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.text,
        },
      }).then((res) => {
        if (res.data!==null) {
          this.tableData = res.data.records || [];
        } else {
          this.tableData=[]
        }
        
      });
    },
    handleChange(item) {
         API.put(`/api/msslyyCart/updateCartAmount/${this.user.id}/${item.id}/${item.cartAmount}`).then(res => {
          if (res.code === '0') {
            
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load()
        })
    },
    // 点击发生的变化
    handleSelectionChange(val) {
      this.deleteItems=[]
      val.forEach(e=>this.deleteItems.push(e.id))
      this.multipleSelection = val; //给定义的数组赋值
    },
    toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
    toCheckout() {
      if (this.multipleSelection.length>0) {
        this.$store.commit('setCheckoutBooks',this.multipleSelection)
        // this.deleteCheckout(false)
        this.$router.push('/shop/checkout')
      } else {
        this.$message({
              type: "error",
              message: "你没有选中任何商品"
            })
      }
      
    },
  },
};
</script>

<style scoped>
.cart {
  margin: 50px auto;
  width: 1200px;
}
.group_btn {
  margin-bottom: 30px;
}
.addDialog .el-input {
  width: 90%;
}
.total_warpper {
  text-align: right;
  margin-top: 30px;
}
h3 {
  margin-top: 10px;
}
</style>